/**
 * 
 */
package org.vectrics.recruiter.user.event;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.employee.Employee;
import org.vectrics.event.Event;
import org.vectrics.event.EventAttachment;
import org.vectrics.event.EventEmailBuilder;
import org.vectrics.event.EventHandler;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.event.JobCandidateEmailBuilder;
import org.vectrics.recruiter.user.Interview;
import org.vectrics.user.EmployeePersonSearchCriteria;

/**
 * @author pgoette
 * Handler que notifica que una persona fue contratada.
 */
public class PersonHiredHandler extends EventHandler {
    // Log
	private transient Logger log = Logger.getLogger(this.getClass());
	
	public PersonHiredHandler() {
		super();
	}

	protected void doHandleEvent(Event event) {
		log.debug("doHandleEvent(Event event) called");
	}

	/**
	 * Generador de mail a enviar
	 */
	protected EventEmailBuilder getEmailBuilder(Event event, Locale locale) {
		return(new HiredEmailBuilder(event, locale, this.getEmployee()));
	}
    
	// Recupera el empleado con el id del attached del evento.
	private Employee getEmployee() {
	    // Si no hay attached no se puede enviar mail
		if (this.getEvent().getAttachments().size() == 0) {
			throw new SystemException("Could not find job attached to job event - event: " + this.getEvent().getDescription());
		}
		// recupero 1 solo attached
		Iterator iter = this.getEvent().getAttachments().iterator();
		EventAttachment attachment = (EventAttachment)iter.next();
		// recupero el empleado y lo devuelvo.
		Employee employee = RecruitServiceLocator.getCompanyService().findEmployee(new Long(attachment.getObjectId()));
		return employee;
	}

	/**
	 * Busca las personas a notificar 
	 */
	protected Set findNotifyPersons() {		
		EmployeePersonSearchCriteria criteria = new EmployeePersonSearchCriteria();
		criteria.addCompanies(CoreServiceLocator.getCompanyService().findAllCompany());
		criteria.setEmployeesOnly(true);
		criteria.addGroupType(CoreServiceLocator.getCompanyService().findCompanyGroupType("finance.admin"));
		criteria.addGroupType(CoreServiceLocator.getCompanyService().findCompanyGroupType("recruiter"));
		criteria.addGroupType(CoreServiceLocator.getCompanyService().findCompanyGroupType("hiring.mgr"));
		Set persons = new HashSet();
		persons.addAll(CoreServiceLocator.getPersonSearcher().findPersons(criteria, 0, 500));
		Employee employee = this.getEmployee();
		if (employee != null){
			if (employee.getJob() != null) {
				if (employee.getJob().getRequester()!=null){
					persons.add(employee.getJob().getRequester());
				}
			}
		}
		return persons;
	}

	
}
